#include <muduo/net/TcpClient.h>
//注意,Muduo库的客户端的connect操作是非阻塞的，所以需要一个计数器类阻塞
#include <memory>
#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/Buffer.h>
#include <muduo/base/Timestamp.h>
#include <muduo/base/CountDownLatch.h>
#include <muduo/net/EventLoopThread.h>
#include<functional>
#include <thread>
#include "Count.hpp"
namespace Dict
{
    static const std::string default_file_path = "./dict.txt";
    using namespace muduo::net;
    using muduo::Timestamp;
    class DictClient
    {
    private:
        //when the connection status is connected,call this function
        void OnConnection(const TcpConnectionPtr& conn)
        {
            std::cout<<"触发OnConnection"<<std::endl;
            if(conn->connected())
            {
                std::cout<<"连接建立成功!"<<std::endl;
                _count.Reduction();
                _conn = conn;
                return;
            }
            std::cout<<"连接关闭!"<<std::endl;
        }
        void OnMessage(const TcpConnectionPtr& conn,Buffer* buff,Timestamp time)
        {
            std::string res = buff->retrieveAllAsString();
            std::cout<<"翻译结果: "<<res<<std::endl;
        }
    public:
        using ptr = std::shared_ptr<DictClient>;
        DictClient(const std::string &ip,
                   int port)
                   :_base_loop(_loop_thread.startLoop()),
                   _client(_base_loop,InetAddress(ip,port),"DictClient"),
                   _count(1)
        {
           
            _client.setConnectionCallback(std::bind(&DictClient::OnConnection,this,std::placeholders::_1));
            _client.setMessageCallback(std::bind(&DictClient::OnMessage,this,
                                        std::placeholders::_1,
                                        std::placeholders::_2,
                                        std::placeholders::_3));
        }
        void connect()
        {
            _client.connect();
            _count.wait();
        }
        void send(const std::string& info)
        {
            _conn->send(info);
        }
    private:
        EventLoopThread _loop_thread;
        EventLoop* _base_loop;
        TcpClient _client;
        TcpConnectionPtr _conn;
        WaitCount _count;
    };
}

int main()
{
    Dict::DictClient client("127.0.0.1",9090);
    client.connect();
    std::string input;
    while(true)
    {
        std::cout<<"请输入: ";
        std::getline(std::cin,input);
        std::cin.clear();
        client.send(input);
    }
    return 0;
}